/*
 * @(#)LuceneHitsIterator.java	0.1 12/28/04
 *
 * Copyright 2004 Fabio Gasparetti. All rights reserved.
 */

package org.tabularium.text.se;

import java.util.Iterator;
import java.io.IOException;
import org.apache.lucene.search.Hits;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;

/**
 *
 */
public class LuceneDocIterator implements DocIterator {
	protected IndexReader reader = null;
	protected Document currentDoc = null;
	protected int indexDoc = 0;
	protected int numDocs;

	LuceneDocIterator(IndexReader reader) {
		this.reader = reader;
		numDocs = reader.numDocs();
	}

	public boolean hasNext() {
		return indexDoc < numDocs;
	}

	/**
	 * Return the next document id (String) in the hit list.
	 */
	public Object next() {
		String id = null;
		if (indexDoc < numDocs) {
			try {
				currentDoc = reader.document(indexDoc);
				id = currentDoc.get("idstorer");
			} catch (Exception ex) {
				indexDoc = numDocs;
				return null;
			}
			indexDoc++;
		} else {
			try {
				// closes IndexReader
				interrupt();
			} catch (Exception ex) {
			}
		}
		return id;
	}

	public void remove() {
		// not implemented
	}

	public byte[] getObj() {
		String ret = currentDoc.get("body");
		return ret != null ? ret.getBytes() : null;
	}

	/**
	 * Invoke this method to close the IndexReader associated with the searcher.
	 */
	public void interrupt() {
		try {
			if (reader != null) {
				reader.close();
				reader = null;
			}
		} catch (IOException ex) {

		}
	}

	protected void finalize() throws Throwable {
		interrupt();
	}
}
